import React, { Component } from 'react';
import { Col, Table, Space, Row, message, Tooltip } from 'antd';
import {
  PlusOutlined,
  DeleteFilled,
  InfoCircleOutlined,
  ExclamationOutlined,
  CheckOutlined,
  QuestionCircleTwoTone,
} from '@ant-design/icons';
import 'braft-editor/dist/index.css';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { getExam, deleteExam, publishExam } from '../../../api3';
import AdvancedSearchForm from '../../../componentJsx/common/searchForm';
import HasPermi from '../../../componentJsx/common/hasPermi';
import NewModal from '../../../componentJsx/common/NewModal';

import 'antd/dist/antd.css';
import { checkAllNumber, getUrl } from '../../../utils';
import '../../../componentCss/component.css';
//import '../index.css';

//字典
import { getDictionaryLabel } from '../../../rudexRou/OperatesCookie.js';
class PracticeManagement extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bottonListLeft: [
        {
          interceptor: 'tmfsExamPlatform:practiceManagement:add',
          type: 'primary',
          clickFn: this.add,
          icon: <PlusOutlined />,
          text: '新增',
        },
        {
          interceptor: 'tmfsExamPlatform:practiceManagement:del',
          type: 'danger',
          clickFn: () => this.showModal('delete'),
          text: '删除',
        },
        {
          interceptor: 'tmfsExamPlatform:practiceManagement:edit',
          clickFn: () => this.showModal('publish'),
          text: '发布',
        },
        {
          interceptor: 'tmfsExamPlatform:practiceManagement:edit',
          clickFn: () => this.showModal('cancelPublish'),
          text: '取消发布',
        },
      ],
      publishModalVisibl: false,
      deleteModalVisible: false, //删除的模态框
      confirmLoading: false, //确认按钮异步等待
      tableLoading: false, //表格等待
      selectedRowKeys: [], //最新表格多选
      selectedRows: [],
      //分页
      total: 0,
      pageSize: 10,
      page: 1,
      //数据
      tableData: [], //最新数据
      //表格列
      tableColumns: [
        {
          title: '',
          dataIndex: 'allSetExaminer',
          key: 'allSetExaminer',
          width:
            sessionStorage.getItem('roleCode').indexOf('tmfs-exam') === -1
              ? 0
              : 40,
          fixed: 'left',
          ellipsis: true,
          align: 'center',
          render: (t, r) => {
            if (t === true) {
              return <CheckOutlined style={{ color: '#0f0' }} />;
            } else if (t === false) {
              return (
                <Tooltip title='需要绑定阅卷人'>
                  <ExclamationOutlined style={{ color: '#f00' }} />
                </Tooltip>
              );
            }
          },
        },
        {
          title: '练习名称',
          dataIndex: 'name',
          key: 'name',
          width: 270,
          fixed: 'left',
          ellipsis: true,
          onCell: (record) => {
            if (
              sessionStorage.getItem('roleCode').indexOf('tmfs-exam') >= 0 &&
              record.createEmpNo == localStorage.getItem('empNo')
            ) {
              return {
                onClick: () => this.showDetail(record),
                style: { color: 'rgb(24, 144, 255)', cursor: 'pointer' },
              };
            }
          },
        },
        {
          title: '练习类型',
          dataIndex: 'open',
          key: 'open',
          ellipsis: true,
          width: 80,
          render: (text) => getDictionaryLabel('testExamType', text),
        },
        {
          title: '练习级别',
          dataIndex: 'level',
          key: 'level',
          width: 80,
          ellipsis: true,
          render: (text) => getDictionaryLabel('examLevel', text),
        },
        {
          title: '练习语言',
          dataIndex: 'language',
          key: 'language',
          ellipsis: true,
          width: 80,
          render: (text) => getDictionaryLabel('language', text),
        },
        {
          title: '有效期',
          dataIndex: 'validityBeginDate',
          key: 'validityBeginDate',
          ellipsis: true,
          width: 200,
          render: (t, r) =>
            t
              ? moment(r.validityBeginDate).format('YYYY-MM-DD') +
                ' 至 ' +
                moment(r.validityEndDate).format('YYYY-MM-DD')
              : r.validity == '1'
              ? '永久有效'
              : '一次性',
        },
        {
          title: '练习开始时间',
          dataIndex: 'startTime',
          key: 'startTime',
          ellipsis: true,
          width: 140,
          render: (text) =>
            text ? moment(text).format('YYYY-MM-DD HH:mm') : text,
        },
        {
          title: '练习时长(min)',
          dataIndex: 'duration',
          key: 'duration',
          ellipsis: true,
          width: 120,
        },
        {
          title: '练习次数',
          dataIndex: 'count',
          key: 'count',
          ellipsis: true,
          width: 80,
          render: (t) => (t == '0' ? '无限次' : t),
        },
        {
          title: '总分',
          dataIndex: 'totalScore',
          key: 'totalScore',
          ellipsis: true,
          width: 60,
        },
        {
          title: '及格分',
          dataIndex: 'passScore',
          key: 'passScore',
          ellipsis: true,
          width: 70,
        },

        {
          title: '题目数',
          dataIndex: 'questionList',
          key: 'questionList',
          ellipsis: true,
          width: 80,
          render: (t, r) => (r.questionList ? r.questionList.length : ''),
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          ellipsis: true,
          width: 80,
          render: (text) => getDictionaryLabel('testExamStatus', text),
        },
        {
          title: '创建人',
          dataIndex: 'createEmpName',
          key: 'createEmpName',
          ellipsis: true,
          width: 140,
          render: (t, r) => t + `(${r.createEmpNo})`,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          ellipsis: true,
          width: 150,
        },
        {
          title: '修改人',
          dataIndex: 'updateUser',
          key: 'updateUser',
          ellipsis: true,
          width: 100,
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          ellipsis: true,
          width: 150,
          // render: (text) =>
          // text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : text,
        },
        {
          title: (
            <Tooltip title='只能操作自己创建的练习'>
              操作 <QuestionCircleTwoTone />
            </Tooltip>
          ),
          dataIndex: 'handle',
          ellipsis: true,
          width:
            sessionStorage.getItem('roleCode').indexOf('tmfs-exam') > -1
              ? 190
              : 0,
          fixed: 'right',
          align: 'center',
          render: (_, record) => (
            <>
              <HasPermi
                bottonData={{
                  disabled:
                    record.status == '0' &&
                    record.createEmpNo == localStorage.getItem('empNo')
                      ? false
                      : true,
                  type: 'link',
                  size: 'small',
                  interceptor: 'tmfsExamPlatform:practiceManagement:edit',
                  clickFn: () => this.edit(record),
                  text: '编辑',
                }}
              />

              <HasPermi
                bottonData={{
                  disabled:
                    record.open == '1' ||
                    record.status == '2' ||
                    record.createEmpNo != localStorage.getItem('empNo')
                      ? true
                      : false,
                  type: 'link',
                  size: 'small',
                  interceptor:
                    'tmfsExamPlatform:practiceManagement:setExaminee',
                  clickFn: () => this.setExaminee(record),
                  text: '参考人',
                }}
              />
              <HasPermi
                bottonData={{
                  disabled:
                    record.createEmpNo != localStorage.getItem('empNo')
                      ? true
                      : false,
                  type: 'link',
                  size: 'small',
                  interceptor: 'tmfsExamPlatform:practiceManagement:setReader',
                  clickFn: () => this.setReader(record),
                  text: '阅卷人',
                }}
              />
            </>
          ),
        },
      ],
      //查询条件
      searchData: {},
      // 查询条件项配置
      searchForm: [
        {
          type: 'input',
          name: '练习名称',
          code: 'name',
          maxLength: 50,
        },
        {
          type: 'select',
          name: '状态',
          code: 'status',
          options: getDictionaryLabel('testExamStatus'),
        },
        {
          type: 'select',
          name: '练习级别',
          code: 'level',
          options: getDictionaryLabel('examLevel'),
        },
      ],
      publishStatus: true,
      record: null,
    };
  }
  addForm = React.createRef();

  //获取最新数据
  getData = () => {
    this.setState({ tableLoading: true });
    let searchData = this.state.searchData;
    let data = {};
    for (const key in searchData) {
      if (searchData[key] || searchData[key] === 0) {
        if (key == 'str') {
          checkAllNumber(searchData.str)
            ? (data.empNo = searchData.str)
            : (data.empName = searchData.str);
        } else {
          data[key] = searchData[key];
        }
      }
    }
    data.type = '0';
    data.pageSize = this.state.pageSize;
    data.currentPage = this.state.page;
    getExam(data)
      .then((res) => {
        if (res.data.code === 200) {
          if (res.data.data) {
            this.setState({
              total: res.data.data.total,
              tableData: res.data.data.list,
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          } else {
            this.setState({
              total: 0,
              tableData: [],
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          }
        } else {
          this.setState({ tableLoading: false });
          message.error(res.data.message || '查询数据失败!');
        }
      })
      .catch((err) => {
        this.setState({ tableLoading: false });
        message.error('查询数据失败!');
      });
  };
  //选择行
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };
  //修改页数changePage
  changePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getData();
    });
  };
  //筛选搜索
  execSearch = (data) => {
    this.setState({ searchData: data, page: 1 }, () => {
      this.getData();
    });
  };
  //设置按钮加载动画开关
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  //隐藏模态框
  hiddenModal = () => {
    this.setState({
      publishModalVisible: false,
      deleteModalVisible: false, //删除的模态框
      confirmLoading: false, //确认按钮异步等待
      record: null,
    });
  };
  //显示模态框
  showModal = (name, record) => {
    if (this.state.selectedRows.length <= 0 && !record) {
      return message.warn('请从列表选择需要操作的练习');
    }
    if (record) {
      this.setState({ record });
    }
    if (name == 'publish') {
      this.setState({
        publishModalVisible: true,
        publishStatus: true,
      });
    } else if (name == 'cancelPublish') {
      this.setState({
        publishModalVisible: true,
        publishStatus: false,
      });
    } else if (name == 'delete') {
      this.setState({
        deleteModalVisible: true,
      });
    }
  };
  //新增
  add = () => {
    getUrl('/TmfsExam/PracticeManagement/AddExam');
  };
  //显示详情
  showDetail = (record) => {
    sessionStorage.setItem('examData', JSON.stringify(record));
    getUrl('/TmfsExam/PracticeManagement/ExamDetail');
  };
  //删除
  delete = () => {
    if (this.state.selectedRows.length <= 0) {
      message.warn('请从列表选择需要删除的练习');
      return;
    }
    this.buttonLoading(true);
    let ids = this.state.selectedRowKeys;
    deleteExam(ids)
      .then((res) => {
        if (res.data.code === 200) {
          message.success('删除成功');
          this.setState({ page: 1 }, () => {
            this.getData();
          });
          this.hiddenModal();
        } else {
          this.hiddenModal();
          this.setState({
            selectedRowKeys: [], //最新表格多选
            selectedRows: [],
          });
          message.error(res.data.message || '删除失败!');
        }
      })
      .catch((err) => {
        this.hiddenModal();
        // this.buttonLoading(false);
        message.error('删除失败!');
      });
  };
  //修改
  edit = (record) => {
    sessionStorage.setItem('examData', JSON.stringify(record));
    getUrl('/TmfsExam/PracticeManagement/EditExam');
  };
  //页面跳转
  setExaminee = (record) => {
    sessionStorage.setItem('examData', JSON.stringify(record));
    getUrl('/TmfsExam/PracticeManagement/SetExaminee');
  };
  setReader = (record) => {
    sessionStorage.setItem('examData', JSON.stringify(record));
    getUrl('/TmfsExam/PracticeManagement/SetReader');
  };
  //发布练习
  publish = () => {
    this.buttonLoading('true');
    let ids = [];
    let publishStatus = this.state.publishStatus ? 1 : 0;
    if (this.state.record) {
      ids = [this.state.record.id];
    } else {
      ids = this.state.selectedRowKeys;
    }
    publishExam({ ids, publishStatus })
      .then((res) => {
        if (res.data.code == 200) {
          message.success('操作成功');
          this.hiddenModal();
          this.getData();
        } else {
          message.error(res.data.message || '操作失败');
          this.hiddenModal();
          this.setState({
            selectedRowKeys: [], //最新表格多选
            selectedRows: [],
          });
        }
      })
      .catch((err) => {
        message.error('操作失败');
        this.hiddenModal();
      });
  };
  //防抖
  debounce(fn, ms = 500) {
    let timeoutId;
    return function() {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        fn.apply(this, arguments);
      }, ms);
    };
  }
  componentWillMount() {}
  componentDidMount() {
    this.getData();
    if (sessionStorage.getItem('examData'))
      sessionStorage.removeItem('examData');
  }
  //组件销毁时取消setState
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    //多选行配置
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div id='evaluate'>
        <div className='myProjectsBody'>
          <div className='bigContent1'>
            <AdvancedSearchForm
              execSearch={this.execSearch}
              formData={this.state.searchForm}
            />
          </div>
          {/* <div className='segmentationDiv'></div> */}
          <div className='tabstyle'>
            <div className='bigContent1' id='projectDetail'>
              <div className='operatingDiv'>
                <Row justify='space-between'>
                  <Col span={16}>
                    <Space size={0}>
                      {this.state.bottonListLeft.map((item) => (
                        <HasPermi key={item.interceptor} bottonData={item} />
                      ))}
                    </Space>
                  </Col>
                </Row>
              </div>

              <div className='tableDiff'>
                <Table
                  rowKey='id'
                  loading={this.state.tableLoading}
                  style={{ marginTop: 10 }}
                  scroll={{ x: '100' }}
                  rowSelection={{ type: 'checkbox', ...rowSelection }}
                  columns={this.state.tableColumns}
                  dataSource={this.state.tableData}
                  pagination={{
                    total: this.state.total,
                    pageSize: this.state.pageSize,
                    current: this.state.page,
                    showSizeChanger: true,
                    onChange: this.changePage,
                    onShowSizeChange: this.changePageSize,
                    showTotal: (total) => '共 ' + total + ' 条',
                  }}
                  bordered
                />
              </div>
            </div>
          </div>
        </div>
        {/* 发布 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: this.state.publishStatus ? '发布练习' : '取消发布练习',
            visible: this.state.publishModalVisible,
            onCancel: this.hiddenModal,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.publish,
                text: this.state.publishStatus ? '发布' : '取消发布',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <InfoCircleOutlined
            style={{
              fontSize: '28px',
              color: '#1890FF',
              float: 'left',
              backgroundColor: '#29F2',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              height: 44,
              lineHeight: '44px',
            }}
          >
            {this.state.publishStatus
              ? '发布选中的练习？'
              : '取消发布选中的练习？'}
          </div>
        </NewModal>
        {/* 删除 */}
        <NewModal
          modalOptions={{
            width: '480px',
            title: '删除提示',
            visible: this.state.deleteModalVisible,
            onCancel: this.hiddenModal,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.delete,
                text: '确认删除',
                type: 'danger',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <DeleteFilled
            style={{
              fontSize: '28px',
              color: '#e00',
              float: 'left',
              backgroundColor: '#f002',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              height: 22,
              lineHeight: '22px',
            }}
          >
            删除后不可恢复，请确认是否删除选中练习？
          </div>
          <div
            style={{
              fontSize: 12,
              marginLeft: 60,
              lineHeight: '22px',
            }}
          >
            1.考试管理员不能删除已发布练习 <br />
            2.系统管理员可删除已发布练习，删除后会将参考人及其成绩一并删除
          </div>
        </NewModal>
      </div>
    );
  }
}

export default PracticeManagement;
